import Ember from 'ember';
import DS from 'ember-data';

/**
{"name":"tree-one","id":401,"localedName":"用户组","description":"树状结构的用户组","treeContent":"{\"jsonLength\":0,\"treeName\":\"tree-one\",\"root\":{\"id\":301,\"n\":\"ROOT\",\"v\":null,\"c\":[{\"id\":302,\"n\":\"ol\",\"v\":null,\"c\":[{\"id\":303,\"n\":\"tl\",\"v\":null,\"c\":[],\"p\":302}],\"p\":301}],\"p\":null}}","_links":{"self":{"href":"http://localhost/api/v1/trees/401"},"treeBlob":{"href":"http://localhost/api/v1/trees/401{?projection}","templated":true}}}
*/

function walker(indexer, current, depth) {
  var c = current.get('c');
  current.id = current.id + "";
  indexer[current.id] = current;
  var nc = [];
  c.forEach((it) => {
    var nit = Ember.Object.create(it);
    nit.set('p', current);
    nc.push(nit);
    walker(indexer, nit, depth + 1);
  });
  current.set('c', nc);
}

export default DS.Model.extend({
  __setupTreeJson: function() {
    var root;
    if (this.get('treeContent')) {
      this.set('treeJson', Ember.$.parseJSON(this.get('treeContent')));
      this.set('treeContent', '');
      this.set('_patch', ["_update_action"]);
      root = Ember.Object.create(this.get('treeJson').root);
      walker(this.get('__indexer'), root, 0);
      this.get('treeJson').root = root;
      this.set('currentNode', this.get('treeJson').root);
    }
  },
  fetched: function() {
    this.__setupTreeJson();
  },
  __indexer: {},
  _patch: DS.attr(),
  _update_action: DS.attr(),
  name: DS.attr("string"),
  localedName: DS.attr("string"),
  description: DS.attr("string"),
  treeContent: DS.attr("string"),
  treeJson: {},
  currentNode: null,
  _insertNode(tua) {
    var gn = Ember.Object.create({
      id: tua.generatedNodeId + "",
      n: tua.name,
      v: tua.body
    });
    var node = this.get('__indexer')[tua.nodeId];

    gn.set('p', node);
    gn.set('c', []);
    node.get('c').pushObject(gn);
    this.get('__indexer')[gn.get('id')] = gn;
  },
  _editNode(tua) {
    var node = this.get('__indexer')[tua.nodeId];
    node.set('n', tua.name);
    node.set('v', tua.body);
  },
  alterNode(tua) {
    if (tua.action === 'ADD') {
      this._insertNode(tua);
    } else if (tua.action === 'EDIT') {
      this._editNode(tua);
    }
  },
  children: Ember.computed('currentNode', '_update_action', function() {
    return this.get('__indexer')[this.get('currentNode').id];
  }),
  validateMe() {
    var n = this.get('name') || "";

    if (!n.length) {
      return {
        fn: "树名称",
        msg: "必须输入树的名称。"
      };
    }
    return null;
  }
});
